package com.syezon.wifikey.enhance;

import android.animation.ValueAnimator;
import android.arch.lifecycle.Observer;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.syezon.wifikey.R;
import com.syezon.wifikey.analysis.AnalysisHelper;
import com.syezon.wifikey.analysis.event.EventEnum;
import com.syezon.wifikey.base.BaseActivity;
import com.syezon.wifikey.enhance.adapter.EnhanceItemAdapter;
import com.syezon.wifikey.enhance.config.EnhanceConfig;
import com.syezon.wifikey.home.InsertFloatAdDialog;
import com.syezon.wifikey.home.ResultHelper;
import com.syezon.wifikey.utils.StatusBarUtil;
import com.syezon.wifikey.view.expandablelayout.ExpandableLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.OnClick;

public class EnhanceActivity extends BaseActivity {

    public static final String ARG_SSID = "ssid";

    private static final int MSG = 1;
    private static final int MSG_FINISH_WIFI_OPT = 2;
    private static final int MSG_FINISH_HARD_OPT = 3;

    private static final long OPT_DUR = 2000;

    @BindView(R.id.ll_back)
    LinearLayout mLlBack;
    @BindView(R.id.rl_top)
    RelativeLayout mRlTop;
    @BindView(R.id.ll_enhance_top_tip)
    LinearLayout mLlEnhance;
    @BindView(R.id.ll_enhance_result)
    LinearLayout mLlEnhanceResult;
    @BindView(R.id.tv_ssid)
    TextView mTvSsid;
    @BindView(R.id.iv_enhance_anim)
    ImageView mIvEnhanceAnim;
    @BindView(R.id.tv_score)
    TextView mTvScore;
    @BindView(R.id.rl_result_layout)
    RelativeLayout mRlResultLayout;
    @BindView(R.id.fl_img_layout_ing)
    FrameLayout mFlEnhancing;
    @BindView(R.id.iv_enhance_big_ing)
    ImageView mIvImgBig;
    @BindView(R.id.iv_enhance_small_ing)
    ImageView mIvImgSmall;
    @BindView(R.id.tv_enhancer_text)
    TextView mTvEnhanceOver;
    @BindView(R.id.ll_hard)
    LinearLayout mLlOptHard;
    @BindView(R.id.expand_hard)
    ExpandableLayout mExpandHard;
    @BindView(R.id.expand_wifi)
    ExpandableLayout mExpandWifi;
    ImageView mIvWifiOptProgress;
    ImageView mIvHardOptProgress;

    private String mSsid;

    private Animation mBigImgAnim;
    private Animation mSmallImgAnim;
    private ValueAnimator mValueAnimator;

    private Handler mAnimHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG:
                    mIvImgSmall.setVisibility(View.VISIBLE);
                    mIvImgSmall.startAnimation(mSmallImgAnim);
                    break;
                case MSG_FINISH_WIFI_OPT:
                    mIvWifiOptProgress.clearAnimation();
                    mIvWifiOptProgress.setVisibility(View.GONE);
                    mExpandWifi.setLayoutAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            mLlOptHard.setVisibility(View.VISIBLE);
                            mExpandHard.startAnimation(AnimationUtils.loadAnimation(EnhanceActivity.this, R.anim.anim_right_in));
                            mIvHardOptProgress.startAnimation(AnimationUtils.loadAnimation(EnhanceActivity.this, R.anim.rotate));
                            mAnimHandler.sendEmptyMessageDelayed(MSG_FINISH_HARD_OPT, OPT_DUR);
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });
                    mExpandWifi.show();
                    break;
                case MSG_FINISH_HARD_OPT:
                    mIvHardOptProgress.clearAnimation();
                    mIvHardOptProgress.setVisibility(View.GONE);
                    mExpandHard.setLayoutAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            showResult();
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });
                    mExpandHard.show();
                    break;
            }
        }
    };

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return true;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_enhance;
    }

    @OnClick({R.id.ll_back, R.id.btn_enhance})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.btn_enhance:
                readyGo(EnhanceHarderActivity.class);
                break;
        }
    }

    @Override
    protected void initViewsAndEvents() {
        StatusBarUtil.setPaddingSmart(this, mRlTop);
        mSsid = getIntent().getStringExtra(ARG_SSID);
        if (TextUtils.isEmpty(mSsid)) {
            finish();
            return;
        }
        mTvSsid.setText(mSsid);

        mLlEnhance.setVisibility(View.VISIBLE);
        mLlEnhanceResult.setVisibility(View.GONE);
        TextView tvWifiOptTitle = mExpandWifi.findViewById(R.id.tv_title);
        tvWifiOptTitle.setText("WiFi优化");
        ImageView ivWifiIndicator = mExpandWifi.findViewById(R.id.iv_indicator);
        ivWifiIndicator.setImageResource(R.drawable.ic_check_wifi_indicator);
        mIvWifiOptProgress = mExpandWifi.findViewById(R.id.iv_progress);
        RecyclerView rvOptWifi = mExpandWifi.findViewById(R.id.rv_list);
        rvOptWifi.setNestedScrollingEnabled(false);
        rvOptWifi.setLayoutManager(new LinearLayoutManager(this));
        EnhanceItemAdapter enhanceItemAdapter = new EnhanceItemAdapter(this);
        enhanceItemAdapter.setData(getWifiOptList());
        rvOptWifi.setAdapter(enhanceItemAdapter);

        mLlOptHard.setVisibility(View.GONE);
        TextView tvHardTitle = mExpandHard.findViewById(R.id.tv_title);
        ImageView iVHardIndicator = mExpandHard.findViewById(R.id.iv_indicator);
        iVHardIndicator.setImageResource(R.drawable.ic_check_hard_indicator);
        tvHardTitle.setText("硬件升级");
        mIvHardOptProgress = mExpandHard.findViewById(R.id.iv_progress);
        RecyclerView rvHardOpt = mExpandHard.findViewById(R.id.rv_list);
        rvHardOpt.setNestedScrollingEnabled(false);
        rvHardOpt.setLayoutManager(new LinearLayoutManager(this));
        EnhanceItemAdapter hardEnhanceAdapter = new EnhanceItemAdapter(this);
        hardEnhanceAdapter.setData(getHardList());
        rvHardOpt.setAdapter(hardEnhanceAdapter);
        AnalysisHelper.onEvent(EventEnum.ENHANCE_SHOW.eventId);
        mExpandWifi.setCanExpand(false);
        mExpandHard.setCanExpand(false);

        wifiOpt();
        getScoreAnimator().start();
    }

    private void wifiOpt() {
        mIvWifiOptProgress.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate));
        mExpandWifi.startAnimation(AnimationUtils.loadAnimation(this, R.anim.anim_right_in));
        mAnimHandler.sendEmptyMessageDelayed(MSG_FINISH_WIFI_OPT, OPT_DUR);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mValueAnimator != null && mValueAnimator.isRunning()) {
            mValueAnimator.cancel();
        }
        mAnimHandler.removeCallbacksAndMessages(null);
    }

    private void startAnim() {
        mBigImgAnim = AnimationUtils.loadAnimation(this, R.anim.anim_bottom_in);
        mSmallImgAnim = AnimationUtils.loadAnimation(this, R.anim.anim_bottom_in);
        mBigImgAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                mIvImgSmall.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mAnimHandler.sendEmptyMessageDelayed(MSG, 200);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        mSmallImgAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mIvImgBig.startAnimation(mBigImgAnim);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        mIvImgBig.startAnimation(mBigImgAnim);
    }


    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus && mIvEnhanceAnim != null && mIvEnhanceAnim.getVisibility() == View.VISIBLE) {
            startOptAnim();
        }
    }

    private void startOptAnim() {
        final Drawable background = mIvEnhanceAnim.getBackground();
        if (background != null && background instanceof AnimationDrawable) {
            ((AnimationDrawable) background).start();
        }
    }

    private void showResult() {
        mLlEnhance.setVisibility(View.GONE);
        mLlEnhanceResult.setVisibility(View.VISIBLE);
        Random random = new Random();
        int result = 95 + random.nextInt(5);
        mTvEnhanceOver.setText(String.format("以增强至%d", result) + "%");
        EnhanceConfig.setEnhance(mSsid, true);
        ResultHelper.showWiFiEnhanceResult(mContext, mSsid);
    }

    private ValueAnimator getScoreAnimator() {
        if (mValueAnimator == null) {
            mValueAnimator = ValueAnimator.ofInt(27, 99).setDuration(4000);
            mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    Object animatedValue = animation.getAnimatedValue();
                    mTvScore.setText(animatedValue + "");
                }
            });
        }

        return mValueAnimator;
    }

    public List<String> getHardList() {
        List<String> list = new ArrayList<>();
        list.add("优化无线模块内核，提高速度");
        list.add("低信号下保持连接，不断线");
        list.add("减少延迟，提升网络稳定，减少网络丢包");
        return list;
    }

    public List<String> getWifiOptList() {
        List<String> list = new ArrayList<>();
        list.add("优化WiFil连接引擎");
        list.add("优化无线网络多线程");
        list.add("减少延迟，提升网络稳定，减少网络丢包");
        list.add("优化WiFi网络选择");
        list.add("优化Host/DNS域服务器");
        list.add("智能调整WAN模式");

        return list;
    }
}
